<template>
  <div>
    <v-card height="170" class="mx-auto">
      <v-container>
        <v-list-item class="py-7">
          <v-list-item-avatar size="96">
            <v-img class="elevation-6" :src="creater.profile_pic"></v-img>
          </v-list-item-avatar>
          <v-list-item-content>
            <v-list-item-title class="headline pb-4 font-weight-bold">{{
              creater.name
            }}</v-list-item-title>
          </v-list-item-content>
          <v-btn v-if="!check" color="primary" @click="follow">+ 关注</v-btn>
          <v-btn v-if="check" color="info" @click="cancel(creater.name)">已关注</v-btn>
        </v-list-item>
      </v-container>
    </v-card>
    <v-container>
      <div class="pt-8">
        <span class="title font-weight-bold">TA的动态</span>
      </div>
      <v-row>
        <v-col
          v-for="article in articles"
          :key="article.pk"
          cols="12"
          md="8"
          class="mt-1"
        >
          <div>
            <v-card
              height="346"
              class="mx-auto"
              @click="$router.push(`/article/${article.pk}`)"
            >
              <v-img :src="article.fields.cover_image" height="194"></v-img>
              <v-list-item>
                <v-list-item-avatar
                  @click="$router.push(`/creater/${article.fields.name[0]}`)"
                >
                  <v-img
                    class="elevation-6"
                    :src="article.fields.name[1]"
                  ></v-img>
                </v-list-item-avatar>
                <v-list-item-content>
                  <v-list-item-title class="headline">{{
                    article.fields.title
                  }}</v-list-item-title>
                  <v-list-item-subtitle>{{
                    article.fields.name[0]
                  }}</v-list-item-subtitle>
                </v-list-item-content>
                <v-btn color="primary">{{ article.fields.category }}</v-btn>
              </v-list-item>

              <v-card-text>
              {{replace(article.fields.content.slice(0, 42))+'...'}}
              </v-card-text>
            </v-card>
          </div>
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script>
export default {
  props: {
    name: {}
  },
  data() {
    return {
      creater: {},
      articles: [],
      check: false,
      no_more: false,
      flag: false, 
      page:1
    };
  },
  created() {
    this.name &&
      this.fetchCreater() &&
      this.fetchCreaterArticle() &&
      this.checkFollow();
      window.addEventListener("scroll", this.scrollHandle, true);
  },
  methods: {
    async fetchCreater() {
      try {
        const res = await this.$http.get(
          `creater_profile/?username=${this.name}`
        );
        this.creater = res.data.list[0].fields;
        this.creater.profile_pic = require(this.creater.profile_pic);
      } catch (e) {
        console.log("图片获取失败");
      }
    },
    async fetchCreaterArticle() {
      try {
        const res = await this.$http.get(
          `article_list_by_name/?name=${this.name}&page=${this.page}`
        );
        if (res.data.error_num === 1) {
          this.no_more = true;
        }
        this.articles = [...this.articles, ...res.data.list];
        this.articles.forEach(art => {
          art.fields.cover_image = require(art.fields.cover_image);
          art.fields.name[1] = require(art.fields.name[1]);
        });
      } catch (e) {
        console.log("图片获取失败");
      }
    },
    more() {
      this.page++;
      this.fetchCreaterArticle();
    },
    replace(str){
      let con = str.replace(/\s*/g, "");  //去掉空格
      let res =con.replace(/<[^>]+>/g, ""); //去掉所有的html标记
      let res1 = res.replace(/↵/g, "");     //去掉所有的↵符号
      let res2 = res1.replace(/[\r\n]/g, "") //去掉回车换行
      return res2
    },
    scrollHandle() {
      // console.log(this.no_more)
      // console.log(this.flag)
      // 获取页面页面的滚动高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 获取页面滚动距离顶部的高度,  window.pageYOffse 兼容苹果
      let scrollTop =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop;
      // 获取页面的可视高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // console.log(scrollHeight);
      // console.log(scrollTop);
      // console.log(clientHeight);
      if (scrollTop + clientHeight >= scrollHeight - 20) {
        // 距离底部还有20的时候执行数据加载
        if (this.flag) return 
					this.flag = true
        if (!this.no_more) {
          console.log("加载数据");
          this.more();
          this.flag = false
        }
      }
    },
    async cancel(follow_name) {
      let name = localStorage.getItem("name");
      const confirm = await this.$dialog.warning({
        text: `确认是否取关${follow_name}?`,
        icon: "fa-exclamation-triangle",
        title: "取消关注"
      });
      if (confirm) {
        const res = await this.$http.get(
          `cancel_follow/?name=${name}&follow_name=${follow_name}`
        );
        if (res.data.error_num === 0) {
          this.$toast({
            text: "取关成功",
            type: "success",
            duration: 3000
          });
          this.check = false
        }
      }
    },
    async follow() {
      let user = {};
      user.name = localStorage.getItem("name");
      console.log(user.name)
      if(user.name === null){
        this.$toast({
          text: "你需要登录才能关注TA",
          type: "warning",
          duration: 3000
        });
        return
      }
      user.follow_name = this.name;
      if(user.name !== user.follow_name){
      const res = await this.$http.post("follow/", user);
      if (res.data.error_num === 0) {
        this.$toast({
          text: "关注成功",
          type: "success",
          duration: 3000
        });
        this.check = true
      }}else{
        this.$toast({
          text: "你不能关注你自己",
          type: "warning",
          duration: 3000
        });
      }
    },
    async checkFollow() {
      const res = await this.$http.get(
        `check_follow/?name=${localStorage.getItem("name")}&follow_name=${
          this.name
        }`
      );
      if (res.data.check === true) {
        this.check = true;
      }
    }
  },
  destroyed() {
    // 页面卸载时移除监听事件
    window.removeEventListener("scroll", this.scrollHandle, true);
    console.log('卸载滚动事件')
  }
};
</script>

<style></style>
